<template>
  <div>
    <button @click="startRecognition">开始语音识别</button>
    <button @click="startRecognitionw">结束语音识别</button>
    <p v-if="recognizedText">您说: {{ recognizedText }}</p>
  </div>
</template>
 
<script>
export default {
  data() {
    return {
      recognizedText: '',
      recognition: null,
    };
  },
  methods: {
    startRecognition() {
      if (!('webkitSpeechRecognition' in window)) {
        alert('您的浏览器不支持语音识别功能');
        return;
      }
      this.recognition = new webkitSpeechRecognition();
      this.recognition.continuous = true; // 连续识别
      this.recognition.interimResults = true; // 返回临时结果
      this.recognition.lang = 'zh-CN'; // 设置语言为中文
 
      this.recognition.onresult = (event) => {
        let transcript = '';
        for (let i = event.resultIndex; i < event.results.length; i++) {
          if (event.results[i].isFinal) {
            transcript += event.results[i][0].transcript;
          } else {
            transcript += event.results[i][0].transcript; // 临时结果也可以显示，取决于需求
          }
        }
        this.recognizedText = transcript; // 更新文本显示
      };
 
      this.recognition.onerror = (event) => {
        console.error('语音识别错误:', event.error);
      };
 
      this.recognition.start(); // 开始语音识别
    },
    startRecognitionw(){
        this.recognition.stop()
    }
  },
  beforeDestroy() {
    if (this.recognition) {
      this.recognition.stop(); // 停止语音识别，清理资源
    }
  },
};
</script>